<template>
  <div :id="id"
       :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
import resize from '@/components/Charts/mixins/resize'

export default {
  name: 'deviceChart',
  mixins:[resize],
  props: {
    data: {
      type: Array,
      default: []
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    }
  },
  data () {
    return {
      id: 'chart1',
      chart: null
    }
  },
  watch: {
    data (val, oval) {
     this.updateChart(val);
    }
  },
  mounted () {
    this.updateChart()
  },
  beforeDestroy () {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    updateChart() {
      if (!this.chart) {
        this.chart = echarts.init(document.getElementById(this.id));
      }
      let xAxisData = []
      let seriesData = []
      let data = this.switchData(this.data);
      xAxisData = data.xAxisData
      seriesData = data.seriesData
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xAxisData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '设备运行数量',
            type: 'bar',
            barWidth: '60%',
            data: seriesData
          }
        ]
      };;
      this.chart.setOption(option)
    },
    switchData (data) {
      let xAxisData = []
      let seriesData = []
      for (var i = 0, a; a = data[i++];) {
        xAxisData.push(a.name);
        seriesData.push(a.count);
      }
      return {xAxisData,seriesData}
    }


  }
}
</script>
